package jpa.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StringUtils {
	public static final Logger LOGGER = Logger.getLogger(StringUtils.class.getName());
	
	public static String toCamelCase(String key) {
		return toCamelCase(key, null);
	}	
	
	public static String toCamelCase(String key, String delimiter) {
		String delim = ((delimiter == null || delimiter == "" || delimiter == ".") ? "\\." : delimiter);
		StringBuilder result = new StringBuilder();
		
		if (key.contains(".")) {
			String[] elements = key.split(delim);
			result.append(elements[0]);
			for (int i = 1; i < elements.length; i++) {
				result.append(toProperCase(elements[i]));
			}
		}
		return result.toString();
	}
	
	private static String toProperCase(String s) {
		return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
	}

	public static String changeDelimiter(String value, String delimiter, String newChar) {
		// default delimiter is '.'
		String delim = ((delimiter == null || delimiter == "" || delimiter == ".") ? "\\." : delimiter);
		// set result to value in the case that the string doesn't containg the delimiter
		String result = value;
		
		if (value.contains(delim)) {
			String[] elements = value.split(delim);
			result += elements[0];
			for (int i = 1; i < elements.length; i++) {
				result += ( "_" + elements[i] );
			}
		}
		return result;
	}
	
	public static String minify(String str) {
		return str.replaceAll(" ", "").replaceAll("\n","").replaceAll("\r", "").replaceAll("\t","");
	}
	
	public static String minify2(String str) {
		return str.replaceAll("[\\r\\n\\t] + \\s", "");
	}

	public static String getText(String url) throws MalformedURLException {
		return getText(new URL(url));
	}	
	
	public static String getText(URL url) {
		StringBuilder sb = new StringBuilder();
		int respCode = urlExist(url); 
		
		if (respCode == HttpURLConnection.HTTP_OK) {
			try {
				BufferedReader in = new  BufferedReader(new InputStreamReader(url.openStream()));
				String content = "";
				while ((content = in.readLine()) != null) {
					sb.append(content);
				}			
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
				LOGGER.log(Level.SEVERE, e.getMessage());
			}
		}
		
		return sb.toString();
	}
	
	public static String getSchema(String url) {
		StringBuilder schema = new StringBuilder();
		try {							
			schema.append( StringUtils.getText(redirectUrl(url)));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}				
		
		return schema.toString();
	}
	
	public static boolean isSet(String o) {
		boolean result = false;
		
		if (o != null && !o.equals("")) {
			result = true;
		}
		
		return result;
	}
	
	public static boolean isSet(URL url) {
		boolean result = false;
		
		if (url != null && !url.equals("")) {
			result = true;
		}
		
		return result;
	}	
	
	public static int urlExist(String url) {		
		URL newUrl = null;
		try {
			newUrl = new URL(url);			 			
		} catch (MalformedURLException e) {
			File f = new File(url);
			if (f.exists()) {
				try {
					newUrl = f.toURI().toURL();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				}
			}
		}
		
		return urlExist(newUrl);
	}
	
	
	public static int urlExist(URL url) {
		int respCode = HttpURLConnection.HTTP_BAD_REQUEST;
		if (isSet(url)) {
			try {
				HttpURLConnection.setFollowRedirects(Boolean.FALSE);
				HttpURLConnection huc = (HttpURLConnection) url.openConnection();
				huc.setRequestMethod("HEAD");				
				respCode = huc.getResponseCode();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return respCode;		
	}
	
	private static String redirectUrl(String url) {
		if (url.endsWith("/")) {
			url = url.substring(0, url.length()-1);
		}		
		
		int pos = url.lastIndexOf("/");
		String mod = getModifier(url.substring(pos, url.length()));
		url = url.substring(0, pos) + "/schema" + mod + ".json";
		
		return url;
	}
	
	private static String getModifier(String str) {
		String modifier = "";
		int dash = str.lastIndexOf("-");
		int dot  = str.lastIndexOf(".");
		modifier = (dash >= 0 && dot >= 0) ? str.substring(dash,dot) : "";
		
		return modifier;
	};
}
